<template>
  <div class="container project">
    <div class="tree">
      <catalog
        :props="data.deptTreeProps"
        :tree-data="store.state.projectCenter.orgList"
        :default-expanded-keys="data.defaultExpandedKeys"
        @on-search="orgSearch"
      />
    </div>
    <div class="data">
      <div class="header">
        <div class="search">
          <el-input
            clearable
            v-model="data.params.projectName"
            placeholder="项目名称/编号"
            style="width: 120px; margin-right: 5px"
          />
          <el-select clearable v-model="data.params.level" placeholder="项目级别">
            <el-option
              v-for="item in store.state.projectCenter.projectDict.XMZX_LEVEL_TYPE"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemValue"
            />
          </el-select>
          <el-select
            clearable
            v-model="data.params.projectType"
            no-data-text="请选择项目级别"
            placeholder="项目类型"
          >
            <el-option
              v-for="item in data.typeList"
              :key="item.itemValue"
              :label="item.itemText"
              :value="item.itemValue"
            />
          </el-select>
          <el-button class="ordinary" @click="search()">搜索</el-button>
        </div>
        <div class="handle">
          <el-button v-limit="'XMZX:XMGL:GCYYXM:EXPORT'" class="ordinary" @click="handleExport()"
            >批量导出</el-button
          >
          <el-button v-limit="'XMZX:XMGL:GCYYXM:DELETE'" type="danger" @click="handleDel()"
            >移除</el-button
          >
          <el-button v-limit="'XMZX:XMGL:GCYYXM:OPEN'" type="primary" @click="openStatus()"
            >启用</el-button
          >
          <el-button v-limit="'XMZX:XMGL:GCYYXM:STOP'" type="primary" @click="closeStatus()"
            >停用</el-button
          >
          <el-button v-limit="'XMZX:XMGL:GCYYXM:ADD'" type="primary" @click="handleAdd()"
            >项目新增</el-button
          >
          <el-button v-limit="'XMZX:XMGL:GCYYXM:CHANGE'" type="primary" @click="handleChange()"
            >项目变更申请</el-button
          >
        </div>
      </div>

      <Table
        :loading="data.isLoading"
        :table-arr="data.allTableData"
        :columns="data.columns"
        :page-size="data.params.size"
        :page-num="data.params.current"
        @selectList="getCurrentList"
        @row-click="handleRowClick"
      >
        <template #status>
          <el-table-column label="状态" width="65">
            <template #default="{ row }">
              <span class="opened-status" v-if="row.projectStatus == 0">已启用</span>
              <span class="stoped-status" v-if="row.projectStatus == 1">停用</span>
              <span v-if="row.projectStatus == 2">未启用</span>
            </template>
          </el-table-column>
        </template>
        <template #operate="{ row }">
          <el-button
            v-limit="'XMZX:XMGL:GCYYXM:EDIT'"
            :disabled="row.projectStatus != 2"
            size="small"
            class="ordinary"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-limit="'XMZX:XMGL:GCYYXM:DETAIL'"
            size="small"
            class="ordinary"
            @click="handleDetail(row)"
            >详情</el-button
          >
        </template>
      </Table>
      <div class="example-pagination-block">
        <el-pagination
          background
          layout="prev, pager, next ,total,sizes,jumper"
          :total="data.total"
          :page-size="data.params.size"
          v-model:current-page="data.params.current"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
      <!-- 项目信息表格 -->
      <el-dialog
        v-model="data.editDialog"
        width="72%"
        top="10vh"
        @close="handleClose"
        :title="data.currentHandle"
        :close-on-click-modal="false"
      >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本信息" name="1">
            <Information
              :title="data.currentHandle"
              :projectCategory="1"
              ref="baseForm"
              v-if="data.editDialog"
            ></Information>
          </el-tab-pane>
          <el-tab-pane label="参与单位" name="2">
            <units v-if="data.editDialog" :title="data.currentHandle"></units>
          </el-tab-pane>
          <el-tab-pane label="相关人员" name="3">
            <personnel v-if="data.editDialog" :title="data.currentHandle"></personnel>
          </el-tab-pane>
          <!-- <el-tab-pane label="项目投入" name="4">
            <investment v-if="data.editDialog" :title="data.currentHandle"></investment>
          </el-tab-pane> -->
          <el-tab-pane label="项目经费" name="4">
            <ProjectBudget v-if="data.editDialog && activeName == '4'&& (store.state.projectCenter.form.level==1||store.state.projectCenter.form.level==3)"></ProjectBudget>
            <ProjectBudget2 v-if="data.editDialog && activeName=='4'&& (store.state.projectCenter.form.level==0)"></ProjectBudget2>
            <ProjectBudget3 v-if="data.editDialog && activeName=='4'&& (store.state.projectCenter.form.level==2||store.state.projectCenter.form.level==4)"></ProjectBudget3>
          </el-tab-pane>
          <el-tab-pane label="项目变更" name="5" v-if="data.currentHandle.indexOf('详情') != -1">
            <record v-if="data.editDialog"></record>
          </el-tab-pane>
          <el-tab-pane label="项目成果" name="6" v-if="data.currentHandle.indexOf('详情') != -1">
            <span> 专利 </span>
            <hr />
            <patent :projectId="data.currentProjectId" v-if="data.editDialog"></patent>
            <span class="awards"> 软件著作权 </span>
            <hr />
            <software :projectId="data.currentProjectId" v-if="data.editDialog"></software>
            <span class="awards"> 学术著作 </span>
            <hr />
            <academic :projectId="data.currentProjectId" v-if="data.editDialog"></academic>
            <span class="awards"> 学术论文 </span>
            <hr />
            <thesis :projectId="data.currentProjectId" v-if="data.editDialog"></thesis>
            <span class="awards"> 科技奖项 </span>
            <hr />
            <awards :projectId="data.currentProjectId" v-if="data.editDialog"></awards>
            <!-- <achievement ></achievement> -->
          </el-tab-pane>
          <!-- <el-tab-pane label="专利" name="6" v-if="data.currentHandle.indexOf('详情') != -1">
            <patent :projectId="data.currentProjectId" v-if="data.editDialog"></patent>
          </el-tab-pane>
          <el-tab-pane label="软件著作权" name="7" v-if="data.currentHandle.indexOf('详情') != -1">
            <software :projectId="data.currentProjectId" v-if="data.editDialog"></software>
          </el-tab-pane>
          <el-tab-pane label="学术著作" name="8" v-if="data.currentHandle.indexOf('详情') != -1">
            <academic :projectId="data.currentProjectId" v-if="data.editDialog"></academic>
          </el-tab-pane>
          <el-tab-pane label="学术论文" name="9" v-if="data.currentHandle.indexOf('详情') != -1">
            <thesis :projectId="data.currentProjectId" v-if="data.editDialog"></thesis>
          </el-tab-pane> -->
        </el-tabs>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.editDialog = false">关闭</el-button>
            <el-button
              v-if="data.currentHandle !== '工程应用项目详情'"
              type="primary"
              @click="handleSave()"
              >保存</el-button
            >
          </span>
        </template>
      </el-dialog>

      <!-- 项目变更申请表格 -->
      <el-dialog
        v-model="data.changeDialog"
        width="60%"
        top="10vh"
        title="项目变更申请"
        :close-on-click-modal="false"
      >
        <change
          ref="changeForm"
          v-if="data.changeDialog"
          :currentData="data.currentList[0]"
        ></change>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.changeDialog = false">关闭</el-button>
            <el-button type="primary" @click="handleSaveChange(0)">保存</el-button>
            <el-button type="primary" @click="handleSaveChange(1)">提交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 导出字段选择 -->
      <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
      ></Export>
    </div>
  </div>
</template>

<script lang="ts">
import { reactive, ref, watch } from 'vue'
import tableData from './tableHeader.json'
import Information from '../components/information.vue'
import units from '../components/units.vue'
import personnel from '../components/personnel.vue'
// import investment from '../components/investment.vue'
import ProjectBudget from '../components/project-budget.vue'
import ProjectBudget2 from '../components/project-budget2.vue'
import ProjectBudget3 from '../components/project-budget3.vue'

import record from '../components/record.vue'
import change from '../components/change.vue'
import patent from '../components/patent.vue'
import software from '../components/software.vue'
import academic from '../components/academic.vue'
import thesis from '../components/thesis.vue'

import { getProjectDetail, getProjectList, getDetailById } from '../../api/project'
import Catalog from '../../components/Catalog/index.vue'
import Table from '../../components/table2/table.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import Export from '@/views/project/components/Export/index.vue'
import { servicesLoading } from '@/views/project/project-manage/loading'
import { startProcess } from '../../api/commom'

import {
  saveProjectChangeProcess,
  submitProjectChange,
  insertProject,
  updateProject,
  delBatchProject,
  openProjectStatus,
  closeProjectStatus,
  exportProjectList,
} from '../../api/project'

export default {
  components: {
    Catalog,
    Table,
    Information,
    units,
    personnel,
    // investment,
    ProjectBudget,
    ProjectBudget2,
    ProjectBudget3,
    record,
    change,
    patent,
    software,
    academic,
    thesis,
    Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    let data = reactive({
      defaultExpandedKeys: [],
      tableTreeData: [],
      currentHandle: '工程应用项目新增',
      params: {
        projectName: '',
        level: '',
        projectType: '',
        createOrgId: '',
        projectCategory: '1',
        projectFlag: '1',
        current: 1,
        size: 10,
      },
      typeList: [] as any,
      total: 0,
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      currentList: [] as any,
      ids: [],
      currentProjectId: '',
      editDialog: false,
      changeDialog: false,
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      dealVisible: false,
      exportDialog: false,
      detailList: [] as any,
    })
    const baseForm = ref()
    const changeForm = ref()

    store.state.projectCenter.form.projectCategory = '1'
    let formData = JSON.parse(JSON.stringify(store.state.projectCenter.form))
    console.log(formData, 'formData')

    const onSearch = async () => {
      data.isLoading = true
      getProjectList(data.params).then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          result.records.map((item) => {
            item.createTime = item.createTime.slice(0, 10)
          })
          data.allTableData = result.records
          data.total = result.total
          data.isLoading = false
        }
      })
    }
    watch(
      () => data.params.level,
      () => {
        data.params.projectType = ''
        data.typeList = []
        console.log(data.params.level, 'form.level变化了')
        store.state.projectCenter.projectDict.XMZX_LEVEL_TYPE?.forEach((obj) => {
          if (obj.itemValue == data.params.level) {
            data.typeList = obj.children
            console.log(data.typeList, 'data.typeList')
          }
        })
      }
    )
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      data.params.current = 1
      onSearch()
    }
    onSearch()
    const defaultProps = {
      children: 'children',
      label: 'label',
    }
    const handleNodeClick = () => {
      console.log('点击组织树结构')
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    const orgSearch = (org) => {
      data.params.current = 1
      data.params.createOrgId = org.id
      console.log(data.params)
      onSearch()
    }
    const search = () => {
      data.params.current = 1
      console.log(data.params)
      onSearch()
    }
    // const projectForm = reactive(store.state.projectCenter.form)
    const handleSave = () => {
      console.log('handleSave')
      // detailData(row.id)
      store.state.projectCenter.form.projectFlag = 1
      store.state.projectCenter.form.projectCategory = 1
      store.state.projectCenter.form.projectCategoryName = '科技研发项目'
      store.state.projectCenter.form.projectStatus = 2
      baseForm.value.submitForm().then((res) => {
        console.log(res)
        if (data.currentHandle == '工程应用项目新增') {
          console.log(store.state.projectCenter.form, 'store.state.projectCenter.form')
          insertProject(store.state.projectCenter.form).then((res) => {
            console.log(res)
            if (res.data.code == 200) {
              onSearch()
              data.editDialog = false
              ElMessage({
                message: '新增成功',
                type: 'success',
              })
            }
          })
        } else if (data.currentHandle == '工程应用项目编辑') {
          updateProject(store.state.projectCenter.form).then((res) => {
            console.log(res)
            if (res.data.code == 200) {
              onSearch()
              data.editDialog = false
              ElMessage({
                message: '修改成功',
                type: 'success',
              })
            }
          })
        }
      })
    }
    const openStatus = () => {
      if (data.ids.length) {
        ElMessageBox.confirm('您确认启用所选中项目吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              openProjectStatus(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '操作成功',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const closeStatus = () => {
      if (data.ids.length) {
        let flag = true
        console.log(data.currentList, 'currentList')
        data.currentList.forEach((obj) => {
          if (obj.projectStatus != '0') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '仅能停用已启用的项目',
            type: 'warning',
          })
          return
        }
        ElMessageBox.confirm('您确认停用所选中项目吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              closeProjectStatus(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '操作成功',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleDel = () => {
      if (data.ids.length) {
        let flag = true
        console.log(data.currentList, 'currentList')
        data.currentList.forEach((obj) => {
          if (obj.projectStatus != '2') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '仅能删除未启用的项目',
            type: 'warning',
          })
          return
        }
        ElMessageBox.confirm('您确认删除所选中项目吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              delBatchProject(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '操作成功',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个项目',
          type: 'warning',
        })
      }
    }
    const handleAdd = () => {
      data.currentHandle = '工程应用项目新增'
      data.editDialog = true
    }
    const handleEdit = (row) => {
      const loading = servicesLoading({ fullscreen: false })
      getProjectDetail({
        id: row.id,
      }).then((res) => {
        console.log(res)
        loading.close()
        data.editDialog = true
        store.state.projectCenter.form = res.data.data
      })
      data.currentHandle = '工程应用项目编辑'
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      data.currentProjectId = row.id
      const loading = servicesLoading({ fullscreen: false })
      getProjectDetail({
        id: row.id,
      }).then((res) => {
        console.log(res)
        loading.close()
        data.editDialog = true
        store.state.projectCenter.form = res.data.data
      })
      data.currentHandle = '工程应用项目详情'
    }
    const handleClose = () => {
      console.log(data.allTableData, 'data.allTableData')
      store.state.projectCenter.form = JSON.parse(JSON.stringify(formData))
      console.log('对话框关闭了', formData)
      data.editDialog = false
      activeName.value = '1'
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          exportProjectList({ ...data.params, ids: data.ids, headList: arr }, '工程化项目数据表格')
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectNumber', title: '项目编号' },
        { fieldName: 'foreignName', title: '项目外文名称' },
        { fieldName: 'projectYear', title: '立项年份' },
        { fieldName: 'departmentName', title: '关联部门' },
        { fieldName: 'formerName', title: '项目曾用名' },
        { fieldName: 'level', title: '项目级别' },
        { fieldName: 'projectTypeName', title: '项目类型' },
        { fieldName: 'projectSourceName', title: '项目来源' },
        { fieldName: 'primaryProfessionTypeName', title: '专业类型（一级）' },
        { fieldName: 'secondaryProfessionTypeName', title: '专业类型（二级）' },
        { fieldName: 'tertiaryProfessionTypeName', title: '专业类型（三级）' },
        { fieldName: 'entrustedUnitName', title: '委托单位' },
        { fieldName: 'internalUnitName', title: '内部承担单位' },
        { fieldName: 'projectLeaderName', title: '项目负责人' },
        { fieldName: 'contactNumber', title: '联系电话' },
        { fieldName: 'startTime', title: '项目开始时间' },
        { fieldName: 'endTime', title: '规定完工日期' },
        { fieldName: 'totalFunding', title: '总经费(万元)' },
        { fieldName: 'fundingCurrencyName', title: '项目总费用币种' },
        { fieldName: 'affiliatedUnitName', title: '所属单位' },
        { fieldName: 'secondaryUnitName', title: '所属二级单位' },
        { fieldName: 'engineeringFieldName', title: '工程领域' },
        { fieldName: 'researchCategoryName', title: '研究类别' },
        { fieldName: 'researchDirectionName', title: '研究方向' },
        { fieldName: 'industrialChainName', title: '产业链' },
        { fieldName: 'remark1', title: '备注' },
        { fieldName: 'researchTarget', title: '研发目标' },
        { fieldName: 'mainResearchContent', title: '主要研究内容' },
      ]
    }
    // const handleExport = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     console.log('批量导出')
    //     exportProjectList({ ...data.params, ids: data.ids }, '工程化项目数据表格')
    //   })
    // }
    const handleChange = () => {
      if (data.ids.length == 1) {
        if (data.currentList[0].projectStatus !== '0') {
          ElMessage({
            message: '只能变更已启用的项目',
            type: 'warning',
          })
          return
        }
        data.changeDialog = true
      } else {
        ElMessage({
          message: '请选择一个项目',
          type: 'warning',
        })
      }
    }
    let changeFormStore = store.state.projectCenter.changeForm
    const handleSaveChange = (index: number) => {
      changeFormStore.projectId = data.currentList[0].id
      changeFormStore.status = 0
      changeFormStore.statusName = '草稿'
      changeForm.value.submitForm().then((res) => {
        console.log(res)
        console.log(changeFormStore, 'store.state.projectCenter.changeForm')
        saveProjectChangeProcess({
          ...changeFormStore,
        }).then((res) => {
          if (res.data.code == 200) {
            let businessKey = res.data.data
            ElMessage({
              message: '保存成功',
              type: 'success',
            })
            data.changeDialog = false
            if (index == 1) {
              //提交项目变更申请，启动流程
              data.editDialog = false
              const loading = servicesLoading({ fullscreen: true })
              startProcess({
                flowKey: 'change-project',
                businessKey: businessKey,
                businessType: 'YW18',
                random: new Date().valueOf(),
              }).then((res) => {
                loading.close()
                if (res.data.code != 200) {
                  ElMessage({
                    message: '流程启动失败,请稍后重试',
                    type: 'warning',
                  })
                } else {
                  data.dealVisible = true
                  deal(businessKey, 1)
                }
              })
            }
          }
        })
      })
    }
    // 处理不通过,提交的过程中.......
    let deal = (id, state) => {
      let times = setInterval(() => {
        getDetailById({
          id: id,
        }).then((res) => {
          const resData = res.data.data
          console.log(
            resData.status == state,
            state == 2 && resData.status == 1,
            'state == 2 ? 1 || 2 : state'
          )
          if (resData.status == state || (state == 2 && resData.status == 1)) {
            data.dealVisible = false
            onSearch()
            ElMessage({
              message: '流程办理成功',
              type: 'success',
            })
            clearTimeout(times)
          }
        })
      }, 3000)
    }
    const handleSubmitChange = () => {
      changeFormStore.projectId = data.currentList[0].id
      changeFormStore.status = 2
      changeFormStore.statusName = '待审批'
      changeForm.value.submitForm().then((res) => {
        console.log(res)
        console.log(changeFormStore, 'store.state.projectCenter.changeForm')
        submitProjectChange({
          ...changeFormStore,
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              message: '提交成功',
              type: 'success',
            })
            data.changeDialog = false
          }
        })
      })
    }
    return {
      store,
      data,
      formData,
      activeName,
      defaultProps,
      baseForm,
      changeForm,
      search,
      orgSearch,
      handleCurrentChange,
      handleSizeChange,
      onSearch,
      getCurrentList,
      handleEdit,
      handleDetail,
      handleRowClick,
      handleDel,
      handleAdd,
      handleChange,
      handleSave,
      handleClose,
      closeExport,
      handleFiled,
      handleExport,
      handleNodeClick,
      openStatus,
      closeStatus,
      handleSaveChange,
      handleSubmitChange,
    }
  },
}
</script>

<style lang="scss" scoped>
.header {
  display: flex;
  justify-content: space-between;
}
.container {
  background-color: white;
  padding: 20px;
  overflow-y: auto;
}
.project {
  display: flex;
  .tree {
    width: 18%;
  }
  .data {
    width: 82%;
  }
}

.pageName {
  font-weight: 700;
}
.el-select {
  width: 100px;
  margin-right: 5px;
}
.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

/deep/.demo-tabs > .el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
:deep(.el-dialog__body) {
  display: block;
  padding: 10px 20px;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid rgb(234, 230, 230);
}
.asd {
  background-color: #5d3e3e;
}
</style>
